import { Tabs, Table, Select, Space, Modal, Button, Tag, Divider } from "antd";
import { useCallback, useEffect, useMemo, useState } from "react";
import axios from "axios";
import _ from "lodash";
import styles from "./index.less";

export default function HomePage() {
  const [db, setDb] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 查询条件
  const [category, setCategory] = useState(); // 类别：固定/移动
  const [npc, setNpc] = useState(); // NPC名称
  const [pos, setPos] = useState(); // 位置
  // 查询结果
  const [result, setResult] = useState([]);

  useEffect(() => {
    axios.get("/npc.json").then(({ data }) => {
      setDb(data);
    });
  }, []);

  const source = useMemo(() => {
    return _.reduce(
      db,
      (arr, v, k) => {
        // k:[固定，移动]
        const columns = _.reduce(
          v.npc,
          (list, o, index) => {
            list.push({
              title: o,
              dataIndex: `${k}${index}`,
              key: `${k}${index}`,
            });
            return list;
          },
          []
        );

        const dataSource = _.reduce(
          v.position,
          (list, pos, index) => {
            const _obj = _.reduce(
              pos,
              (obj, p, i) => {
                obj[`${k}${i}`] = p;
                return obj;
              },
              {}
            );
            _obj.key = `${k}${index}`;
            list.push(_obj);
            return list;
          },
          []
        );
        arr.push({
          key: k,
          label: k,
          children: (
            <Table
              dataSource={dataSource}
              columns={columns}
              pagination={false}
              size="small"
            />
          ),
        });
        return arr;
      },
      []
    );
  }, [db]);

  const filterOption = useCallback(
    (input, option) =>
      (option?.label ?? "").toLowerCase().includes(input.toLowerCase()),
    []
  );

  const categoryChange = (value) => {
    // 类型变化
    setCategory(value);
  };

  const categorys = useMemo(() => {
    const list = _.reduce(
      db,
      (arr, o, k) => {
        arr.push({ label: k, value: k });
        return arr;
      },
      []
    );
    setCategory(list[0]?.value);
    return list;
  }, [db]);

  const npcList = useMemo(() => {
    let list = [];
    if (category) {
      const arr = db[category]["npc"];
      list = _.map(arr, (o) => ({ label: o, value: o }));
    }
    setNpc(list[0]?.value);
    return list;
  }, [db, category]);

  const posList = useMemo(() => {
    let list = [];
    if (category) {
      // 获取位置列表
      const arr = db[category]["position"];
      const all = [];
      _.each(arr, (map) => {
        _.each(map, (o) => {
          if (!_.includes(all, o)) {
            all.push(o);
          }
        });
      });
      list = _.map(all, (o) => ({ label: o, value: o }));
    }
    setPos(list[0]?.value);
    return list;
  }, [db, category]);

  useEffect(() => {
    if (category && npc && pos && db) {
      const npcList = db[category]["npc"];
      // 获取当前NPC所在列索引
      const npcIndex = npcList.indexOf(npc);
      const posList = db[category]["position"];

      let tmp = null;
      for (let i = 0; i < posList.length; i++) {
        const npcPosList = posList[i];
        if (npcPosList[npcIndex] == pos) {
          tmp = npcPosList;
          break;
        }
      }

      if (tmp) {
        const _result = _.reduce(
          npcList,
          (arr, o, i) => {
            arr.push({ npc: o, pos: tmp[i] });
            return arr;
          },
          []
        );
        setResult(_result);
      } else {
        setResult([]);
      }
    }
  }, [category, npc, pos, db]);

  return (
    <div className={styles.box}>
      <div className={styles.head}>
        <Button
          type="primary"
          onClick={() => {
            setIsModalOpen(true);
          }}
        >
          查询NPC
        </Button>
      </div>
      <Tabs items={source} />
      <Modal
        title="家园NPC坐标查询"
        open={isModalOpen}
        footer={null}
        onCancel={() => {
          setIsModalOpen(false);
        }}
      >
        <Space wrap>
          <div>
            <span> 类型:</span>
            <Select
              style={{
                width: 80,
              }}
              onChange={categoryChange}
              value={category}
              options={categorys}
            />
          </div>
          <div>
            NPC:
            <Select
              style={{
                width: 100,
              }}
              onChange={(v) => {
                setNpc(v);
              }}
              value={npc}
              options={npcList}
            />
          </div>
          <div>
            所在位置:
            <Select
              style={{
                width: 140,
              }}
              // showSearch
              // filterOption={filterOption}
              onChange={(v) => {
                setPos(v);
              }}
              value={pos}
              options={posList}
            />
          </div>
        </Space>
        <Divider />
        <Space wrap>
          {result.map(({ npc, pos }) => (
            <Tag color="processing" key={npc}>
              {npc}:{pos}
            </Tag>
          ))}
        </Space>
      </Modal>
    </div>
  );
}
